package com.cq.hd.order.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.cq.hd.common.enums.biz.OrderSettleBillTradeTypeEnum;
import com.cq.hd.order.api.vo.OrderSettleBillVo;
import com.cq.hd.order.factory.orderSettle.OrderSettleBillFactory;
import com.cq.hd.order.po.TbOrderSettleBillPo;
import com.cq.hd.order.service.HfRemoteCallerService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.List;
import java.util.concurrent.CompletableFuture;
import java.util.stream.Collectors;

/**
 * @author much
 * @since 2024/05/09 23:06
 */
@Slf4j
@Service
public class HfRemoteCallerServiceImpl implements HfRemoteCallerService {

    /**
     * 异步调用结算打款
     */
    @Override
    public void asyncCallByOrderSettle(List<TbOrderSettleBillPo> orderSettleBills) {
        if (CollectionUtils.isEmpty(orderSettleBills)) {
            return;
        }
        try {
            // 过滤掉金额=0和补贴账单（补贴在另外的任务处理）
            List<TbOrderSettleBillPo> dataList = orderSettleBills.stream()
                    .filter(e -> e.getTradeAmt().compareTo(BigDecimal.ZERO) > 0
                            && !OrderSettleBillTradeTypeEnum.SUBSIDY_AMT.getValue().equals(e.getTradeType()))
                    .collect(Collectors.toList());

            CompletableFuture<Void> future = CompletableFuture.runAsync(new CallHfTransferTask(dataList));

            future.thenRun(() -> {
                System.out.println("hfSettlePay异步处理完成.");
            });
        } catch (Exception e) {
            log.error(e.getMessage(), e);
        }
    }

    static class CallHfTransferTask implements Runnable {

        private List<TbOrderSettleBillPo> dataList;

        CallHfTransferTask(List<TbOrderSettleBillPo> dataList) {
            this.dataList = dataList;
        }

        @Override
        public void run() {
            for (TbOrderSettleBillPo orderSettleBill : dataList) {
                OrderSettleBillVo orderSettleBillVo = BeanUtil.copyProperties(orderSettleBill, OrderSettleBillVo.class);
                if (!OrderSettleBillFactory.getOrderSelectHandler(orderSettleBill.getTradeType()).transactAmt(orderSettleBillVo)) {
                    log.error("hfSettlePay处理失败，orderSettleBillId：{}", orderSettleBill.getId());
                }
            }
        }
    }

}
